<?php

namespace App\Listeners;

use App\Events\OrderComputedDistribution;
use App\Models\ShareProduct;
use App\Service\UserFlowService;
use Flaravel\FLaravelSms;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class OrderComputedDistributionListen
{
    /**
     * Handle the event.
     *
     * @param  OrderComputedDistribution  $event
     * @return void
     */
    public function handle(OrderComputedDistribution $event)
    {
        // 订单
        $order = $event->order;

        // 被分享者下单
        $user = $event->order->user;

        // 分享的用户
        $member = $event->user;

        // 类型
        $type = $event->type;

        // 获取商品信息
        $items = $order->items()->with('product')->get();

        Log::info("--------------进入商品分销:{$order->order_sn}---------------");

        DB::transaction(function () use ($order, $user, $member, $items, $type) {
            if ($items->isNotEmpty() && $member->id != $user->id) {
                foreach ($items as $item) {
                    $product = $item->product;
                    // 获取分享者分享的商品
                    $sharedProduct = ShareProduct::where('product_id', $product->id)
                        ->where('member_id', $member->id)
                        ->where('status', 1)
                        ->first();
                    // 数据异常
                    if (is_null($sharedProduct)) {
                        Log::alert('分销商品数据未找到');
                        Log::alert('未找到的分销商品ID:'. $product->id);
                        Log::alert('分享者ID:'. $member->id);
                        Log::alert('被分享者ID:'. $user->id);
                        Log::alert('订单ID:'. $item->order_id);
                        continue;
                    } else {
                        // 进入分销
                        if ($type == 1) {  // 记录信息
                            // 将分销数据补全
                            $sharedProduct->update([
                                'order_id' => $item->order_id,
                                'amount' => $item->amount,
                                'product_sku_name' => $item->product_sku_name,
                                'product_sku_price' => bcmul($item->price, $item->amount, 2),
                                'shared_id' => $user->id,
                            ]);
                            Log::alert('分销商品数据绑定成功');
                            Log::alert('绑定者ID:'. $user->id);
                        } else if ($type == 2) {  // 分销
                            $res = $sharedProduct->update([
                                'status' => 2
                            ]);
                            if ($res) {
                                // 计算分销的金额
                                $icon =  bcmul($sharedProduct->product_sku_price, bcdiv($sharedProduct->product_commission_ratio,100,2),2);
                                $allIcom = bcmul($icon,$sharedProduct->amount,2);
                                $member->increment('gourd_coin',$allIcom);
                                // 记录流水
                                $desc = sprintf('分享产品收益葫芦币+%d', $allIcom);
                                (new UserFlowService())->create($member, 2, $desc, $allIcom);
                                if ($member->phone) {
                                    $res = FLaravelSms::notice($member->phone,'PointsToAccountNotice',[
                                        'product_name' => Str::limit( $product->title,'20')
                                    ]);
                                    Log::alert('短信发送状态'.$res);
                                }
                                Log::alert('分销商品数据成功');
                                Log::alert('分享者ID:'. $member->id);
                                Log::alert('被分享者ID:'. $user->id);
                                Log::alert('购买数量:'. $sharedProduct->amount);
                                Log::alert('获取葫芦币:'. $allIcom);
                            }
                        }
                    }
                }
            } else {
                Log::alert('分销商品数据失败');
                Log::alert('分享者ID:'.$member->id);
                Log::alert('被分享者ID:'. $user->id);
            }
        });
        Log::info("----------------------商品分销结束-----------------------");
    }
}
